﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.WebControls;

namespace SPDesigner.Policy
{
    public class SPDAdminJobManager : GlobalAdminPageBase
    {

        protected Literal ErrorMessageLiteral;
        protected WebApplicationSelector WebAppSelector;
        protected Repeater SiteCollectionRepeater;
        protected DropDownList IntervalMinutesDropDownList;

        protected override void OnLoad(EventArgs e)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
        }
        protected void WebAppSelector_OnContextChange(object sender, EventArgs e)
        {
            InitSiteCollectionSelector();

            // Try to get the settings out for the job and init the drop-down.
            //foreach (SPJobDefinition job in this.WebAppSelector.CurrentItem.JobDefinitions)
            //{
            //    if (job.Title == Globals.JobName)
            //        IntervalMinutesDropDownList.Items.FindByValue(((SPMinuteSchedule)job.Schedule).Interval.ToString()).Selected = true;
            //}
        }

        private void InitSiteCollectionSelector()
        {
            if (this.WebAppSelector.CurrentItem.Sites.Count > 0)
            {
                this.SiteCollectionRepeater.DataSource = this.WebAppSelector.CurrentItem.Sites;
                this.SiteCollectionRepeater.DataBind();
            }
        }

        protected void SiteCollectionRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                SPSite siteCollection = e.Item.DataItem as SPSite;

                TextBox siteCollectionIdTextBox = e.Item.FindControl("SiteCollectionIdTextBox") as TextBox;
                siteCollectionIdTextBox.Text = siteCollection.ID.ToString();

                Literal siteCollectionName = e.Item.FindControl("SiteCollectionLiteral") as Literal;
                siteCollectionName.Text = siteCollection.Url;

                RadioButtonList jobStatusList = e.Item.FindControl("JobStatusList") as RadioButtonList;
                if(SiteCollectionHasSPDEnabled(siteCollection).HasValue)
                    if (SiteCollectionHasSPDEnabled(siteCollection).Value)
                        jobStatusList.SelectedValue = "Enabled";
                    else
                        jobStatusList.SelectedValue = "Disabled";
            }
        }
        protected void SetTimerJobsButton_OnClick(object sender, EventArgs e)
        {
            SPWebApplication webapp = this.WebAppSelector.CurrentItem;
            SPDAdminJobSettings settings = webapp.GetChild<SPDAdminJobSettings>(Globals.SettingsID);

             // Delete the job for the current Web application.
            //foreach (SPJobDefinition oldJob in this.WebAppSelector.CurrentItem.JobDefinitions)
            //{
            //    if (oldJob.Title == Globals.JobName)
            //        oldJob.Delete();
            //}
            // Purge the configuration data for the current Web application.
            settings.SiteCollectionsEnabled.Clear();
            settings.Update();

            // Get a list of all the site collections that were requested to be enabled.
           var selectedSiteCollections = GetSelectedSiteCollections();
            if (selectedSiteCollections.Count > 0)
            {

                using (SPLongOperation operation = new SPLongOperation(this.Page))
                {
                    operation.LeadingHTML = "SharePoint Designer Permission";
                    operation.TrailingHTML = "Please wait while the permissions are applied for the web applicaiton " + webapp.Name;
                    operation.Begin();


                    foreach (SPSite site in webapp.Sites)
                    {
                        if (selectedSiteCollections.ContainsKey(site.ID))
                            SPDAdminLogic.SetSPSiteSPD(site, selectedSiteCollections[site.ID]);
                        site.Dispose();
                    }

                    // Add the settings.
                    foreach (var siteCollectionID in selectedSiteCollections)
                    {
                        settings.SiteCollectionsEnabled.Add(siteCollectionID.Key, siteCollectionID.Value);
                    }
                    settings.Update();

                    var permjobfeatguid = new Guid("669c6e44-ca3b-4e41-8993-ededd86ba52e");

                    if (webapp.Features[permjobfeatguid] == null)
                        webapp.Features.Add(permjobfeatguid);


                    operation.End("/_admin/SPDPolicy/SPDAdminJobManager.aspx");

                }


               
            }
        }

        private Dictionary<Guid, bool> GetSelectedSiteCollections()
        {
            Dictionary<Guid, bool> selectedSiteCollections = new Dictionary<Guid, bool>();

            TextBox siteCollectionIdTextBox;
            RadioButtonList siteCollectionList;
            foreach (RepeaterItem item in SiteCollectionRepeater.Items)
            {
                siteCollectionIdTextBox = item.FindControl("SiteCollectionIdTextBox") as TextBox;
                siteCollectionList = item.FindControl("JobStatusList") as RadioButtonList;
                selectedSiteCollections.Add(new Guid(siteCollectionIdTextBox.Text),siteCollectionList.SelectedValue == "Enabled");
            }

            return selectedSiteCollections;
        }



        private bool? SiteCollectionHasSPDEnabled(SPSite siteCollection)
        {
            try
            {
                SPDAdminJobSettings settings = this.WebAppSelector.CurrentItem.GetChild<SPDAdminJobSettings>(Globals.SettingsID);

                // If no settings previously created, create them now.
                if (settings == null)
                {
                    SPPersistedObject parent = this.WebAppSelector.CurrentItem;
                    settings = new SPDAdminJobSettings(Globals.SettingsID, parent, Guid.NewGuid());
                    settings.Update();
                }
                if (!settings.SiteCollectionsEnabled.ContainsKey(siteCollection.ID))
                    return null;
                return settings.SiteCollectionsEnabled[siteCollection.ID];
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = "A new storage location had to be created. Please go back to the Application Management page and come back in before doing any work.";
                return null;
            }
        }


    }

}